package com.rui.study.micro.usermanager.config;

import com.rui.study.micro.usermanager.config.filter.CleanCookieFilter;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletListenerRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.filter.DelegatingFilterProxy;

import javax.servlet.Filter;
import java.util.Collection;
import java.util.EventListener;
import java.util.HashSet;

@Configuration
public class WebConfig {

    /**************************************************
     *                    LISTENER                    *
     **************************************************/

//    @Bean(name = "globalListener")
//    public ServletListenerRegistrationBean globalListenerRegistrationBean() {
//        GlobalListener listener = new GlobalListener();
//        ServletListenerRegistrationBean listenerRegistrationBean = buildListener(listener);
//        listenerRegistrationBean.setOrder(0);
//        return listenerRegistrationBean;
//    }



    /**************************************************
     *                     FILTER                     *
     **************************************************/

    @Bean
    public FilterRegistrationBean shiroFilterRegistrationBean() {
        DelegatingFilterProxy filter = new DelegatingFilterProxy();

        HashSet<String> urlPatterns = new HashSet<String>();
        urlPatterns.add("/*");

        return buildFilter("shiroFilter", filter, urlPatterns);
    }

    @Bean
    public FilterRegistrationBean cleanCookieFilterRegistrationBean() {
        CleanCookieFilter filter = new CleanCookieFilter();

        HashSet<String> urlPatterns = new HashSet<String>();
        urlPatterns.add("/*");

        return buildFilter("cleanCookieFilter", filter, urlPatterns);
    }



    /**************************************************
     *                 PRIVATE METHOD                 *
     **************************************************/

    private ServletListenerRegistrationBean buildListener(EventListener listener) {
        ServletListenerRegistrationBean listenerRegistrationBean = new ServletListenerRegistrationBean();
        listenerRegistrationBean.setListener(listener);
        return listenerRegistrationBean;
    }

    private FilterRegistrationBean buildFilter(String filterName, Filter filter, Collection urlPatterns) {
        FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();
        filterRegistrationBean.setName(filterName);
        filterRegistrationBean.setFilter(filter);
        filterRegistrationBean.setUrlPatterns(urlPatterns);
        return filterRegistrationBean;
    }
}
